#coding:utf-8
"""
*   Coder    : Dzlua
*   Email    : 505544956@qq.com
*   Time     : 2017/09/19
"""
#--------------------#
from utilities import helper
import config
#--------------------#
class User(helper.db.Model):
    __tablename__ = 'users'
    id = helper.db.Column(helper.db.Integer, primary_key = True)
    username = helper.db.Column(helper.db.String(32), index = True)
    password_hash = helper.db.Column(helper.db.String(128))
    
    def hash_password(self, password):
        self.password_hash = helper.pwd_context.encrypt(password)
    def verify_password(self, password):
        return helper.pwd_context.verify(password, self.password_hash)
    def generate_auth_token(self, expiration=600):
        s = helper.Serializer(config.SECRET_KEY, expires_in=expiration)
        return s.dumps({'id': self.id})
    @staticmethod
    def verify_auth_token(token):
        s = helper.Serializer(config.SECRET_KEY)
        try:
            data = s.loads(token)
        except helper.SignatureExpired:
            return None    # valid token, but expired
        except helper.BadSignature:
            return None    # invalid token
        user = User.query.get(data['id'])
        return user
#--------------------#
@helper.auth.verify_password
def verify_password(username_or_token, password):
    user = User.verify_auth_token(username_or_token)
    if not user:
        user = User.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    helper.g.user = user
    return True
#--------------------#
